﻿using Md.Api.DDD;
using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysUser.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysUser;
/// <summary>
/// 添加系统用户服务
/// </summary>
public class InsertSysUserService : ApiBase<RequestInsertSysUserModel>
{
    /// <summary>
    /// 系统用户仓储
    /// </summary>
    public SysUserRep sysUserRep { get; set; }
    /// <summary>
    /// 系统用户角色关联仓储
    /// </summary>
    public SysUserRoleRep sysUserRoleRep { get; set; }
    /// <summary>
    /// 系统用户岗位关联仓储
    /// </summary>
    public SysUserPostRep sysUserPostRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var model = new SysUserModel();

        model.DeptId = Parameter.DeptId;
        model.UserName = Parameter.UserName;
        model.NickName = Parameter.NickName;
        model.UserType = Parameter.UserType;
        model.Email = Parameter.Email;
        model.Phonenumber = Parameter.Phonenumber;
        model.Sex = Parameter.Sex;
        model.Avatar = Parameter.Avatar;

        if (!string.IsNullOrWhiteSpace(Parameter.Password))
        {
            model.Password = EncrptyHelp.MD5Pwd(Parameter.Password);
        }
        else
        {
            model.Password = EncrptyHelp.MD5Pwd("md123456");
        }

        model.Status = Parameter.Status;
        model.DelFlag = "0";
        model.CreateBy = userKey?.ToString();
        model.CreateTime = DateTime.Now;
        model.Remark = Parameter.Remark;

        var res = sysUserRep.Insert(model);

        if (Convert.ToInt64(res) > 0)
        {
            if (Parameter.RoleIds != null && Parameter.RoleIds.Length > 0)
            {
                sysUserRoleRep.DeleteRoleByUserId(Convert.ToInt64(res));

                foreach (var roleId in Parameter.RoleIds)
                {
                    var userRoleModel = new SysUserRoleModel();

                    userRoleModel.UserId = Convert.ToInt64(res);
                    userRoleModel.RoleId = roleId;

                    sysUserRoleRep.Insert(userRoleModel);
                }
            }

            if (Parameter.PostIds != null && Parameter.PostIds.Length > 0)
            {
                sysUserPostRep.DeletePostByUserId(Convert.ToInt64(res));

                foreach (var postId in Parameter.PostIds)
                {
                    var userPostModel = new SysUserPostModel();

                    userPostModel.UserId = Convert.ToInt64(res);
                    userPostModel.PostId = postId;

                    sysUserPostRep.Insert(userPostModel);
                }
            }

            Result.Data = sysUserRep.GetSysUserByUserId(Convert.ToInt64(res));
        }
        else
        {
            Result.Data = res;
        }
    }
}

